import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { inventoryCheck, inventoryCheckItems, inventory, products } from '@/lib/schema';
import { eq, and, desc } from 'drizzle-orm';

export async function GET() {
  try {
    const checks = await db
      .select()
      .from(inventoryCheck)
      .orderBy(desc(inventoryCheck.createdAt))
      .limit(50);

    return NextResponse.json(checks);
  } catch (error) {
    console.error('获取盘点列表失败:', error);
    return NextResponse.json(
      { error: '获取盘点列表失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    let notes = '';
    
    // 尝试解析请求体，如果没有请求体则使用空值
    try {
      const body = await request.json();
      notes = body.notes || '';
    } catch (e) {
      // 请求体为空或无效JSON，使用默认值
      notes = '';
    }
    
    // 生成盘点单号
    const checkNumber = `CHK-${Date.now()}-${Math.random().toString(36).substr(2, 4).toUpperCase()}`;
    
    // 创建盘点单
    const [newCheck] = await db
      .insert(inventoryCheck)
      .values({
        checkNumber: checkNumber,
        checkDate: new Date(),
        status: 'draft',
        notes: notes,
        createdBy: 'user',
      })
      .returning();

    // 获取所有库存商品
    const inventoryItems = await db
      .select({
        productId: inventory.productId,
        quantity: inventory.quantity,
        productName: products.name,
        productSku: products.sku,
      })
      .from(inventory)
      .leftJoin(products, eq(inventory.productId, products.id));

    // 创建盘点明细
    const checkItems = inventoryItems.map(item => ({
      checkId: newCheck.id,
      productId: item.productId,
      systemQuantity: item.quantity || 0,
      actualQuantity: item.quantity || 0, // 默认实际数量等于系统数量
      discrepancy: 0,
      notes: '',
    }));

    if (checkItems.length > 0) {
      await db
        .insert(inventoryCheckItems)
        .values(checkItems);
    }

    // 更新盘点单统计
    await db
      .update(inventoryCheck)
      .set({
        totalItems: inventoryItems.length,
        checkedItems: 0,
        discrepancies: 0,
      })
      .where(eq(inventoryCheck.id, newCheck.id));

    return NextResponse.json(newCheck, { status: 201 });

  } catch (error: any) {
    console.error('创建盘点单失败:', error);
    return NextResponse.json(
      { error: '创建盘点单失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}